{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用分支限界法求解 0-1 背包问题\n",
    "\n",
    "使用优先队列搜索，单位价值高的优先级高."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基本设置\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 58 [20, 10, 9, 9, 17, 16, 9, 12, 9, 12] [19, 16, 23, 5, 19, 13, 8, 4, 14, 21]\n"
     ]
    }
   ],
   "source": [
    "# 数据读取\n",
    "import re\n",
    "def LoadData(path):\n",
    "    '''\n",
    "    数据读取。\n",
    "    Input:\n",
    "    - path: 数据路径.\n",
    "    \n",
    "    Return:\n",
    "    - cache: a list contains (n,c,w,v)\n",
    "    '''\n",
    "    cache = []\n",
    "    with open(path,'r') as f:  \n",
    "         for i in range(4):\n",
    "            x = re.findall(r'\\d+',f.readline())\n",
    "            x = [int(i) for i in x]\n",
    "            cache.append(x)\n",
    "    return cache\n",
    "    \n",
    "path = 'test2.txt'\n",
    "n,c,w,v = LoadData(path)\n",
    "n = n[0]\n",
    "c = c[0]\n",
    "print(n,c,w,v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "93"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import heapq\n",
    "def BranchAndBound(n,c,w,v):\n",
    "    '''\n",
    "    优先队列分支限界法.\n",
    "    Input:\n",
    "    - n: 物品数量.\n",
    "    - w: 物品重量.\n",
    "    - c: 背包容量.\n",
    "    - v: 物品价值.\n",
    "    \n",
    "    Return:\n",
    "    - value: 最优价值.\n",
    "    '''\n",
    "    values = 0\n",
    "    state = c\n",
    "    pqueue = [] # 优先队列\n",
    "    vrate = [v[i]/w[i] for i in range(n)] # 价值率\n",
    "    ind = 0\n",
    "    heapq.heappush(pqueue,(-vrate[ind],values,state,ind))\n",
    "    while len(pqueue)!=0:\n",
    "        vra,value,state,ind = heapq.heappop(pqueue)\n",
    "        vra = - vra\n",
    "        if ind != n-1:\n",
    "            if (state - w[ind]) >= 0:\n",
    "                heapq.heappush(pqueue,(-vrate[ind+1],value+v[ind],state-w[ind],ind+1))\n",
    "            heapq.heappush(pqueue,(-vrate[ind+1],value,state,ind+1))\n",
    "        if ind == n-1:           \n",
    "            if (state - w[ind]) >= 0:\n",
    "                if value + v[ind] > values:\n",
    "                    values = value + v[ind]\n",
    "            else:\n",
    "                if value > values:\n",
    "                    values = value\n",
    "    return values\n",
    "\n",
    "BranchAndBound(n,c,w,v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "torch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
